package com.whfc.ms.api.sys.controller;

import com.whfc.common.base.BaseController;
import com.whfc.common.enums.SysRulePlatform;
import com.whfc.common.result.ListData;
import com.whfc.common.result.PageData;
import com.whfc.common.result.Result;
import com.whfc.common.result.ResultUtil;
import com.whfc.common.util.SessionAttr;
import com.whfc.fuum.dto.SysDeptRoleDTO;
import com.whfc.fuum.dto.SysRuleDTO;
import com.whfc.fuum.dto.SysUserDTO;
import com.whfc.fuum.entity.SysEmpUser;
import com.whfc.fuum.entity.SysUser;
import com.whfc.fuum.param.*;
import com.whfc.ms.api.sys.service.MsSysUserService;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @Description:
 * @author: xugcheng
 * @version: 1.0
 * @date: 2019/7/16 11:05
 */
@RestController
@RequestMapping("/ms/api/user")
public class SysUserController extends BaseController {

    @Autowired
    private MsSysUserService sysUserService;

    /**
     * 根据查询条件查找用户列表
     *
     * @param sysUser
     * @param sysUserParam
     * @return
     */
    @RequiresPermissions(value = {"sys/user", "sys-gscx/user"}, logical = Logical.OR)
    @GetMapping("/list")
    public Result list(@SessionAttribute(SessionAttr.MS_USER) SysUser sysUser, SysUserListParam sysUserParam) {
        logger.info("根据查询条件获取用户列表，username:{},data:{}", sysUser.getUsername(), sysUserParam.toString());
        PageData<SysUserDTO> pageData = sysUserService.list(sysUser, sysUserParam);
        return ResultUtil.success(pageData);
    }

    /**
     * 账号详情
     *
     * @param sysUser
     * @param userId
     * @return
     */
    @RequiresPermissions(value = {"sys/user", "sys-gscx/user"}, logical = Logical.OR)
    @GetMapping("detail")
    public Result queryUserById(@SessionAttribute(SessionAttr.MS_USER) SysUser sysUser,
                                @RequestParam(value = "userId", required = false) Integer userId,
                                @RequestParam(value = "empId", required = false, defaultValue = "0") Integer empId) {
        logger.info("获取账号详情，username:{},userId:{},empId:{}", sysUser.getUsername(), userId, empId);
        if (userId == null && empId != 0){
            SysEmpUser empUser = sysUserService.getEmpUser(empId);
            SysUserDTO userDTO = sysUserService.queryUserById(empUser.getSysUserId());
            return ResultUtil.success(userDTO);
        }else {
            SysUserDTO userDTO = sysUserService.queryUserById(userId);
            return ResultUtil.success(userDTO);
        }
    }

    /**
     * 删除用户
     *
     * @param sysUser
     * @param userId
     * @return
     */
    @RequiresPermissions(value = {"sys/user/del", "sys-gscx/user/del"}, logical = Logical.OR)
    @PostMapping("/del/{userId}")
    public Result del(@SessionAttribute(SessionAttr.MS_USER) SysUser sysUser, @PathVariable("userId") Integer userId) {
        logger.info("删除用户，username:{},userId:{}", sysUser.getUsername(), userId);
        sysUserService.del(sysUser, userId);
        return ResultUtil.success();
    }

    /**
     * 编辑用户
     *
     * @param sysUser
     * @param sysUserEdit
     * @return
     */
    @RequiresPermissions(value = {"sys/user/edit", "sys-gscx/user/edit"}, logical = Logical.OR)
    @PostMapping("/edit")
    public Result edit(@SessionAttribute(SessionAttr.MS_USER) SysUser sysUser, @Validated @RequestBody SysUserEdit sysUserEdit) {
        logger.info("编辑用户，username:{},data:{}", sysUser.getUsername(), sysUserEdit);
        sysUserService.edit(sysUserEdit);
        return ResultUtil.success();
    }

    /**
     * 禁用或者启用账号
     *
     * @param sysUser
     * @param request
     * @return
     */
    @RequiresPermissions(value = {"sys/user/enable", "sys-gscx/user/enable"}, logical = Logical.OR)
    @PostMapping("/enable")
    public Result enable(@SessionAttribute(SessionAttr.MS_USER) SysUser sysUser, @Validated @RequestBody SysUserEnable request) {
        logger.info("禁用或启动账号，username:{},data:{}", sysUser.getUsername(), request);
        sysUserService.enable(request.getUserId(), request.getStatus(), sysUser.getId());
        return ResultUtil.success();
    }

    /**
     * 重置密码
     *
     * @param sysUser
     * @param request
     * @return
     */
    @RequiresPermissions(value = {"sys/user/resetPassword", "sys-gscx/user/resetPassword"}, logical = Logical.OR)
    @PostMapping("/resetPassword")
    public Result resetPassword(@SessionAttribute(SessionAttr.MS_USER) SysUser sysUser, @Validated @RequestBody SysResetPasswordParam request) {
        logger.info("重置密码，操作者:{}，参数userId:{},password:*****", sysUser.getUsername(), request.getUserId());
        sysUserService.resetPassword(request);
        return ResultUtil.success();
    }

    @RequiresPermissions(value = {"sys/userRole/edit", "sys-gscx/userRole/edit"}, logical = Logical.OR)
    @PostMapping("/dept/add")
    public Result addDept(@SessionAttribute(SessionAttr.MS_USER) SysUser sysUser, @RequestBody @Validated SysUserDeptRolesAdd request) {
        logger.info("新增用户组织机构，username:{},request:{}", sysUser.getUsername(), request);
        sysUserService.addDeptRoles(request);
        return ResultUtil.success();
    }


    @RequiresPermissions(value = {"sys/userRole/edit", "sys-gscx/userRole/edit"}, logical = Logical.OR)
    @PostMapping("/dept/roles/edit")
    public Result deptRoleEdit(@SessionAttribute(SessionAttr.MS_USER) SysUser sysUser,
                               @Validated @RequestBody SysUserRoleEdit request) {
        logger.info("编辑用户组织机构角色，username:{},request:{}", sysUser.getUsername(), request);
        sysUserService.editDeptRoles(request);
        return ResultUtil.success();
    }

    @GetMapping("/dept/roles")
    public Result getUserDeptRoles(@SessionAttribute(SessionAttr.MS_USER) SysUser sysUser,
                                   @RequestParam(value = "userId", required = false) Integer userId,
                                   @RequestParam(value = "deptId", required = false) Integer deptId,
                                    @RequestParam(value = "empId", required = false, defaultValue = "0") Integer empId) {
        logger.info("获取用户部门角色，username:{},userId:{},deptId:{},empId{}", sysUser.getUsername(), userId, deptId,empId);
        if (userId == null && empId != 0){
            SysEmpUser empUser = sysUserService.getEmpUser(empId);
            userId = empUser.getSysUserId();
        }
        List<SysDeptRoleDTO> sysDeptRoleList = sysUserService.getUserDeptRoles(sysUser,userId, deptId);
        return ResultUtil.success(new ListData<>(sysDeptRoleList));
    }

    /**
     * 修改密码
     *
     * @param sysUser
     * @return
     */
    @PostMapping("/updatePassword")
    public Result updatePassword(@SessionAttribute(SessionAttr.MS_USER) SysUser sysUser, @Validated @RequestBody UpdatePasswordParam request) {
        logger.info("修改密码，username:{}", sysUser.getUsername());
        sysUserService.updatePassword(sysUser, request);
        return ResultUtil.success();
    }

    /**
     * 查询当前用户的权限列表
     *
     * @param loginUser
     * @return
     */
    @GetMapping("/rule/list")
    public Result getAllRuleList(@SessionAttribute(SessionAttr.MS_USER) SysUser loginUser) {
        logger.info("查询所有权限列表,loginUser:{}", loginUser.getUsername());
        List<SysRuleDTO> ruleDTOS = sysUserService.getUserRuleList(loginUser, SysRulePlatform.MS.getValue());
        ListData listData = new ListData(ruleDTOS);
        return ResultUtil.success(listData);
    }

    /**
     * 查询当前用户权限列表
     *
     * @param sysUser
     * @param deptId
     * @return
     */
    @GetMapping("/rules")
    public Result userRules(@SessionAttribute(SessionAttr.MS_USER) SysUser sysUser, @RequestParam("deptId") Integer deptId) {
        logger.info("获取用户权限列表，loginer:{},deptId:{}", sysUser.getUsername(), deptId);
        List<SysRuleDTO> list = sysUserService.getUserRuleListByDeptId(sysUser, SysRulePlatform.MS.getValue(), deptId);
        return ResultUtil.success(new ListData<>(list));
    }
}
